package cn.gotom.core.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;

@Singleton
public final class GuicePersistFilter implements Filter
{
	protected final Logger log = Logger.getLogger(getClass());
	private final UnitOfWork unitOfWork;
	private final PersistService persistService;

	@Inject
	public GuicePersistFilter(UnitOfWork unitOfWork, PersistService persistService)
	{
		this.unitOfWork = unitOfWork;
		this.persistService = persistService;
	}

	public void init(FilterConfig filterConfig) throws ServletException
	{
		persistService.start();
		log.info("persistService.start");
	}

	public void destroy()
	{
		persistService.stop();
		log.info("persistService.stop");
	}

	public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException
	{
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String URI = request.getRequestURI();
		boolean begin = false;
		try
		{
			if (!URI.startsWith(request.getContextPath() + "/template/"))
			{
				begin = true;
				log.debug("unitOfWork.begin() " + URI);
				unitOfWork.begin();
			}
		}
		catch (Exception e)
		{
			log.error(URI, e);
			e.printStackTrace();
		}
		try
		{
			filterChain.doFilter(servletRequest, servletResponse);
		}
		finally
		{
			if (begin)
			{
				unitOfWork.end();
				log.debug("unitOfWork.end() " + URI);
			}
		}
	}
}
